package com.chunayev.numerology.gui.table.listener;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;


import com.chunayev.numerology.domain.PositionSummary;
import com.chunayev.numerology.gui.frame.SummaryFrame;
import com.chunayev.numerology.gui.table.NumerologicTable;
import com.chunayev.numerology.gui.table.TablePositionCalculator;
import com.chunayev.numerology.gui.util.ComponentDisplayManager;
import com.chunayev.numerology.util.db.DBInitializer;
import com.sleepycat.je.DatabaseException;

/**
 * @author Sergey Chunayev
 */
public class NumerologicTableMouseDoubleClickListener extends MouseAdapter {
    
    private static final SummaryFrame summaryFrame;
    
    static {
        try {
            summaryFrame = new SummaryFrame();
        } catch (DatabaseException e) {
            throw new RuntimeException(e);
        }
    }
    
    /*
     * (non-Javadoc)
     * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
     */
    @Override
    public void mouseClicked(final MouseEvent e) {
        super.mouseClicked(e);
        final NumerologicTable table = (NumerologicTable) e.getSource();
        if (e.getClickCount() == 2) {
            final int row = table.rowAtPoint(e.getPoint());
            final int column = table.columnAtPoint(e.getPoint());
            if (column > 0) {
                try {
                    int position = TablePositionCalculator.calculatePosition(
                            row, column);
                    PositionSummary positionSummary = DBInitializer.SUMMARY_PRIMARY_INDEX
                            .get((long) position);
                    
                    summaryFrame.setPositionSummary(positionSummary);
                    summaryFrame.pack();
                    ComponentDisplayManager.centralize(summaryFrame);
                    summaryFrame.setVisible(true);
                    
                } catch (final DatabaseException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}
